package servlet;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import Request.*;
import RequestHandler.RequestHandler;


public class RequestProcess extends HttpServlet {
    
	private RequestHandler rh = RequestHandler.getInstance();

    private ServletContext sc;
    private String savePath;
    
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		System.out.println("doGet invoked");
		String requestType = req.getParameter("type");
		
		if(requestType.equals("clickingSearch"))
			handleclickingSearchRequest(req, resp);
		else if(requestType.equals("clickingSell"))
			handleclickingSellRequest(req, resp);
		else if(requestType.equals("pcenter"))
			handlePcenterRequest(req, resp);
		else if(requestType.equals("search"))
			handleSearchRequest(req, resp);
		else if(requestType.equals("searchPage"))
			handleSearchPageRequest(req, resp);
		else if(requestType.equals("itemDetail"))
			handleItemDetailRequest(req, resp);
		
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		postProcess(req, resp);
	}

/* doGet method*/
	// clicking Search
	private void handleclickingSearchRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{		
		int uid = Integer.parseInt(req.getParameter("uid"));
		int sid = Integer.parseInt(req.getParameter("sid"));

		System.out.println("clickingSearch: uid: " + uid +", sid: " + sid);
		
		String nextJSP = "/search.jsp";
		
		RequestFactory rf = new RequestFactory(RequestType.GETCATEGORY);
		rf.init(uid, sid, req, resp,this,nextJSP);  // 
		rh.handleRequest(rf.getRequest());
		
		try{
			synchronized (this) {
				this.wait();
			}
		}catch (InterruptedException e){
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	// clicking sell Request
	private void handleclickingSellRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{		
		int uid = Integer.parseInt(req.getParameter("uid"));
		int sid = Integer.parseInt(req.getParameter("sid"));

		System.out.println("clickingSearch: uid: " + uid +", sid: " + sid);
		
		String nextJSP = "/sell.jsp";
		
		RequestFactory rf = new RequestFactory(RequestType.GETCATEGORY);
		rf.init(uid, sid, req, resp,this,nextJSP);  // 
		rh.handleRequest(rf.getRequest());
		
		try{
			synchronized (this) {
				this.wait();
			}
		}catch (InterruptedException e){
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	// personal centre information
	private void handlePcenterRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {		
		int uid = Integer.parseInt(req.getParameter("uid"));
		int sid = Integer.parseInt(req.getParameter("sid"));
		
		System.out.println("handle pcenter, username-" + uid +",sid-"+ sid);
		
		RequestFactory rf = new RequestFactory(RequestType.VIEWCENTRE);
		rf.init(uid, sid, req, resp,this,"");  // 
		rh.handleRequest(rf.getRequest());
		try{
			synchronized (this) {
				this.wait();
			}
		}catch (InterruptedException e)		{
			e.printStackTrace();
		}
	}	
	
	//search page click search button linking to search detail page
	private void handleSearchRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{		
		int uid = Integer.parseInt(req.getParameter("uid"));
		int sid  = Integer.parseInt(req.getParameter("sid"));
		req.setAttribute("currentpage", 1);
		String keyword = req.getParameter("keywords");
		int category = Integer.parseInt(req.getParameter("category"));
		int min = 0;
		int max = 0;
		
		if (req.getParameter("minimumprice")=="" || req.getParameter("minimumprice")==null)
			min = -1;
		else 
			min = Integer.parseInt(req.getParameter("minimumprice"))*100;
		
		if(req.getParameter("maximumprice")=="" || req.getParameter("maximumprice")==null)
			max = -1;
		else
			max = Integer.parseInt(req.getParameter("maximumprice"))*100;		
		boolean isBo = req.getParameter("isbuyout") != null;
		System.out.println("---------------"+isBo);
		RequestFactory rf = new RequestFactory(RequestType.SEARCH, keyword, category, min,max,isBo);	
		rf.init(uid, sid, req, resp, this, "/searchresult.jsp");  
		rh.handleRequest(rf.getRequest());
		try{
			synchronized (this) {
				this.wait();
			}
		}catch (InterruptedException e)		{
			e.printStackTrace();
		}
	}
	
	
	
	//searchresult page click page number linking to the corresponding page
	private void handleSearchPageRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{		
		int uid = Integer.parseInt(req.getParameter("uid"));
		int sid  = Integer.parseInt(req.getParameter("sid"));
		int page = Integer.parseInt(req.getParameter("page"));
		int currentPage = Integer.parseInt(req.getParameter("page"));
		req.setAttribute("currentpage", currentPage);
		
		RequestFactory rf = new RequestFactory(RequestType.SEARCHPAGE, page );		
		
		rf.init(uid, sid, req, resp, this, ""); 
		rh.handleRequest(rf.getRequest());
		try{
			synchronized (this) {
				this.wait();
			}
		}catch (InterruptedException e)		{
			e.printStackTrace();
		}
	}
	
	
	
	

	
	private void handleItemDetailRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{		
		
		int uid = Integer.parseInt(req.getParameter("uid"));
		int sid  = Integer.parseInt(req.getParameter("sid"));
		int iid = Integer.parseInt(req.getParameter("iid"));
		
		RequestFactory rf = new RequestFactory(RequestType.VIEWDETAIL, iid);
		rf.init(uid, sid, req, resp, this, "/itemdetail.jsp");
		rh.handleRequest(rf.getRequest());
		try{
			synchronized (this) {
				this.wait();
			}
		}catch (InterruptedException e)		{
			e.printStackTrace();
		}
		
		
		
		
		
	}
/* doPost method*/
	// login
	private void handleLoginRequest(HttpServletRequest req, HttpServletResponse resp,HashMap<String,String> formMap) throws ServletException, IOException{		
		String username = formMap.get("username");
		String password = formMap.get("password");
		
		System.out.println("login username: " + username +","+ password);
		
		RequestFactory rf = new RequestFactory(RequestType.LOGIN, username, password);
		rf.init(-1, -1, req, resp,this,"");  // 
		rh.handleRequest(rf.getRequest());
		try{
			synchronized (this) {
				this.wait();
			}
		}catch (InterruptedException e)		{
			e.printStackTrace();
		}
	}
	
/* doPost method*/
	// comment
	private void handleCommentRequest(HttpServletRequest req, HttpServletResponse resp,HashMap<String,String> formMap) throws ServletException, IOException{		
		int uid = Integer.parseInt(formMap.get("uid"));
		int sid  = Integer.parseInt(formMap.get("sid"));
		int iid = Integer.parseInt(formMap.get("iid"));
		String comment = formMap.get("comment");
		
		
		RequestFactory rf = new RequestFactory(RequestType.COMMENT, iid, comment);
		rf.init(uid, sid, req, resp,this,"");  // 
		rh.handleRequest(rf.getRequest());
		try{
			synchronized (this) {
				this.wait();
			}
		}catch (InterruptedException e)		{
			e.printStackTrace();
		}
	}	
	
	
/* doPost method*/
	// bid
	private void handleBidRequest(HttpServletRequest req, HttpServletResponse resp,HashMap<String,String> formMap) throws ServletException, IOException{		
		int uid = Integer.parseInt(formMap.get("uid"));
		int sid  = Integer.parseInt(formMap.get("sid"));
		int iid = Integer.parseInt(formMap.get("iid"));
		int price = (int)((Float.parseFloat(formMap.get("price")))*100);
		
		RequestFactory rf = new RequestFactory(RequestType.BID, iid, price);
		rf.init(uid, sid, req, resp,this,"");  // 
		rh.handleRequest(rf.getRequest());
		try{
			synchronized (this) {
				this.wait();
			}
		}catch (InterruptedException e)		{
			e.printStackTrace();
		}
	}	

	
	
	/* doPost method*/
	// buyout
	private void handleBuyoutRequest(HttpServletRequest req, HttpServletResponse resp,HashMap<String,String> formMap) throws ServletException, IOException{		
		int uid = Integer.parseInt(formMap.get("uid"));
		int sid  = Integer.parseInt(formMap.get("sid"));
		int iid = Integer.parseInt(formMap.get("iid"));
		
		
		RequestFactory rf = new RequestFactory(RequestType.BUYOUT, iid);
		rf.init(uid, sid, req, resp,this,"");  // 
		rh.handleRequest(rf.getRequest());
		try{
			synchronized (this) {
				this.wait();
			}
		}catch (InterruptedException e)		{
			e.printStackTrace();
		}
	}	
	
	
	
	// logout
	private void handleLogoutRequest(HttpServletRequest req, HttpServletResponse resp,HashMap<String,String> formMap) throws ServletException, IOException{		
		int uid = Integer.parseInt(formMap.get("uid"));
		int sid  = Integer.parseInt(formMap.get("sid"));
		
		System.out.println("logout username: " + uid +","+ sid);
	
		RequestFactory rf = new RequestFactory(RequestType.LOGOUT);
		rf.init(uid, sid, req, resp,this,"");  // 
		rh.handleRequest(rf.getRequest());
		try{
			synchronized (this) {
				this.wait();
			}
		}catch (InterruptedException e)		{
			e.printStackTrace();
		}
	}
	// register
	private void handleRegisterRequest(HttpServletRequest req, HttpServletResponse resp,HashMap<String,String> formMap){		
		String username = formMap.get("username");
		String password = formMap.get("password");
		String name = formMap.get("name");
		String telephone = formMap.get("telephone");
		String address = formMap.get("address");
		String email = formMap.get("email");
		
		System.out.println();
		System.out.println(username +","+ password +","+ name +","+ telephone +","+ address +","+ email);
		
		RequestFactory rf = new RequestFactory(RequestType.REGISTER, username, password, name, telephone, address, email);
		rf.init(-1, -1, req, resp,this,"");  // 
		rh.handleRequest(rf.getRequest());
		try{
			synchronized (this) {
				this.wait();
			}
		}catch (InterruptedException e)		{
			e.printStackTrace();
		}
		

	}
	// sell
	private void handleSellRequest(HttpServletRequest req, HttpServletResponse resp,HashMap<String,String> formMap) throws ServletException, IOException{		
		int uid = Integer.parseInt(formMap.get("uid"));
		int sid  = Integer.parseInt(formMap.get("sid"));
		
		String itemname = formMap.get("itemname");    
		int category = Integer.parseInt(formMap.get("category"));
		String itemdetail= formMap.get("itemdetail");
		int duration = Integer.parseInt(formMap.get("duration"));
		
		int co =  (int)(Float.parseFloat(formMap.get("co"))*100);
		
		String pp = formMap.get("page");
		String image = formMap.get("image");
		
		System.out.println();
		System.out.println("co-" + co);
		
		int bo = 0;

		if((formMap.get("bo") == null) || (formMap.get("bo").equals(""))){
			bo = 0;
		}else{
			bo = (int)(Float.parseFloat(formMap.get("bo"))*100);
		}
		
		System.out.println("sell");
		System.out.println(category);		
        
		RequestFactory rf;
		
		if(image.equals("noPicture")){
			rf = new RequestFactory(RequestType.SELL, itemname, category, null, itemdetail,co, bo, duration);
		} else{
			rf = new RequestFactory(RequestType.SELL, itemname, category, image, itemdetail,co, bo, duration);
		}
		
		rf.init(uid, sid, req, resp,this,"");  // 
		rh.handleRequest(rf.getRequest());
		try{
			synchronized (this) {
				this.wait();
			}
		}catch (InterruptedException e)		{
			e.printStackTrace();
		}
	}
	
	private void postProcess(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
		HashMap<String,String> formMap = new HashMap<String,String>();
		req.setCharacterEncoding("UTF-8");
        
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
        
        try {
            List<FileItem> items = servletFileUpload.parseRequest(req);
            Iterator<FileItem> iterator = items.iterator();
            
            while (iterator.hasNext()) {
                FileItem item = (FileItem) iterator.next();
                if(item.isFormField()){//parameter
                	formMap.put(item.getFieldName(),item.getString("UTF-8"));
                }else {
                    if(item.getName()!=null && !item.getName().equals("")){//upload file
                        
                    	Date d = new Date();
                    	long longtime = d.getTime();
                    	
                    	System.out.println("longtime"+longtime);

                    	String newFileName = req.getSession().getAttribute("uid").toString()+"_" + longtime + ".jpg";   // change file name
                        
                        File file = new File(sc.getRealPath("/")+savePath,newFileName);
                        item.write(file);//write file
                        
                        formMap.put("image",newFileName);
//                        formMap.put("message","Picture Upload Sucess");
                    }else{
                    	formMap.put("image","noPicture");
//                    	formMap.put("message","No Picture Uploaded");
                    }
                }
            }
            System.out.println("formMap = "+formMap); 
        } catch (Exception e) {
            e.printStackTrace();
            formMap.put("image","noPicture");
//            formMap.put("message","Picture Upload Failed");
        }
        
        System.out.println("formMap = "+formMap);
        
		String requestType = formMap.get("type");
		
		if(requestType.equals("login"))
			handleLoginRequest(req, resp,formMap);
		else if(requestType.equals("logout"))
			handleLogoutRequest(req, resp,formMap);
		else if(requestType.equals("register"))
			handleRegisterRequest(req, resp,formMap);
		else if(requestType.equals("sell"))
			handleSellRequest(req, resp,formMap);
		else if(requestType.equals("comment"))
			handleCommentRequest(req, resp, formMap);
		else if(requestType.equals("bid"))
			handleBidRequest(req, resp, formMap);
		else if(requestType.equals("buyout"))
			handleBuyoutRequest(req, resp, formMap);
	}

    @Override
    public void init(ServletConfig config) throws ServletException {
//       savePath = config.getInitParameter("savePath");
        savePath = "img";
        sc = config.getServletContext();        
    }
	
}
